package com.family.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.family.domain.Area;
import com.family.domain.Food;
import com.family.domain.FoodType;
import com.family.domain.Order;
import com.family.domain.SubFood;
import com.family.domain.User;
import com.family.domain.Desk;
import com.family.inter.IArea;
import com.family.inter.IDesk;
import com.family.inter.IFood;
import com.family.inter.IFoodtype;
import com.family.inter.IOrder;
import com.family.tools.DateFormatUtils;
import com.family.tools.Print;

@Controller
public class FoodAction {

    Map pmap = new HashMap<String, String>();

    @Resource
    IFoodtype ifoodtype;

    @Resource
    IFood  ifood;

    @Resource
    IArea  iarea;

    @Resource
    IDesk  idesk;

    @Resource
    IOrder  iorder;

    @ResponseBody
    @RequestMapping("/add_foodtype")
    public String addFoodType(FoodType foodtype)
    {
        UUID uuid = UUID.randomUUID();
        foodtype.setId(uuid.toString());

        String count = ifoodtype.getMax();
        if(count==null)
        {
            foodtype.setSort("0");
        }else
        {
            String sort =String.valueOf((Integer.parseInt(count)+1));
            foodtype.setSort(sort);
        }


        foodtype.setFlag("1");
        ifoodtype.addFoodType(foodtype);


        return "success";
    }

    @ResponseBody
    @RequestMapping("/add_area")
    public String add_area(Area area)
    {
        UUID uuid = UUID.randomUUID();
        area.setId(uuid.toString());

        iarea.addArea(area);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/add_desk")
    public String add_desk(String areaid,Desk desk)
    {
        UUID uuid = UUID.randomUUID();
        desk.setId(uuid.toString());

        Map map = new HashMap<String, String>();
        map.put("areaid", areaid);
        map.put("deskid", uuid.toString());

        idesk.addAreaDesk(map);

        desk.setFlag("0");
        desk.setDname(desk.getDname().trim());
        desk.setCount(desk.getCount().trim());
        idesk.addDesk(desk);

        return "success";
    }


    @ResponseBody
    @RequestMapping("/add_desk_nogroup")
    public String add_desk_nogroup(Desk desk)
    {
        UUID uuid = UUID.randomUUID();
        desk.setId(uuid.toString());

        desk.setFlag("0");
        idesk.addDesk(desk);

        return "success";
    }


    @ResponseBody
    @RequestMapping("/movedesk")
    public String movedesk(String areaid,String  deskid)
    {
        //System.out.println("areaid="+areaid+" deskid="+deskid);
        Map map = new HashMap<String, String>();
        map.put("areaid", areaid);
        map.put("deskid", deskid);
        idesk.moveDesk(map);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/adddeskGroup")
    public String adddeskGroup(String areaid,String  deskid)
    {
        Map map = new HashMap<String, String>();
        map.put("areaid", areaid);
        map.put("deskid", deskid);
        idesk.moveDesk(map);
        idesk.addAreaDesk(map);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/addfood")
    public String addfood(Food food)
    {
        UUID uuid = UUID.randomUUID();
        food.setId(uuid.toString());
        String strlist="";

        /*去空格*/
        food.setPrice(food.getPrice().trim());

        String imglist = food.getImage().substring(0, food.getImage().length()-1);
        String[]  arr = imglist.split(",");
        for(String str:arr){
            String fileName = str.substring(str.lastIndexOf("\\")+1);
            strlist+=fileName+",";
        }

        food.setImage(strlist.substring(0,strlist.length()-1));

        //System.out.println("id="+food.getId()+"foodname="+food.getFoodname()+"img="+food.getImage()+"price="+food.getPrice());
        food.setScore("0");

        ifood.addFood(food);

        return uuid.toString();
    }

    @ResponseBody
    @RequestMapping("/addfoodgroup")
    public String addfoodgroup(String foodtypeid,String foodid)
    {
        Map map = new HashMap<String, String>();
        map.put("foodtypeid", foodtypeid);
        map.put("foodid", foodid);
        ifood.delFoodGroup(map);
        ifood.addFoodGroup(map);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/delfoodgroup")
    public String delfoodgroup(String foodtypeid,String foodid)
    {
        Map map = new HashMap<String, String>();
        map.put("foodtypeid", foodtypeid);
        map.put("foodid", foodid);
        ifood.delFoodGroup(map);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/udpatefood")
    public String udpateFood(Food food)
    {
        ifood.update(food);
        return "保存成功";
    }

    @ResponseBody
    @RequestMapping("/delDesk")
    public String delDesk(String id)
    {
        idesk.delDesk(id);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/update_foodtype")
    public String upFoodType(FoodType foodtype)
    {
        ////System.out.println("name="+foodtype.getTypename()+"  id="+foodtype.getId());
        ifoodtype.update(foodtype);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/update_MaxSort")
    public String updateMax(String sort,String id)
    {
        List<FoodType> arr = ifoodtype.getMaxSort(sort);
        FoodType nextSort = arr.get(0);

        /*当前 记录*/
        pmap.put("sort", nextSort.getSort());
        pmap.put("id", id);
        ifoodtype.updateSort(pmap);

        /*下一记录*/
        pmap.put("sort", sort);
        pmap.put("id", nextSort.getId());
        ifoodtype.updateSort(pmap);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/update_MinSort")
    public String updateMin(String sort,String id)
    {
        List<FoodType> arr = ifoodtype.getMinSort(sort);
        FoodType nextSort = arr.get(0);

        /*当前 记录*/
        pmap.put("sort", nextSort.getSort());
        pmap.put("id", id);
        ifoodtype.updateSort(pmap);

        /*下一记录*/
        pmap.put("sort", sort);
        pmap.put("id", nextSort.getId());
        ifoodtype.updateSort(pmap);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/delete_foodtype")
    public String delete_foodtype(String id,HttpServletResponse response)
    {
        ifood.delFoodGroupByid(id);
        ifoodtype.deleteFoodType(id);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/order_car")
    public String order_car(String orderid)
    {
        iorder.upOrdFoodStat(orderid);

        Order order = iorder.getOrderById(orderid);
        System.out.println(order+"  "+orderid);
        List<SubFood>  list = ifood.getFoodListByOrderid(order.getId());

        Desk desk = idesk.getDeskById(order.getDeskid());
        System.out.println(desk+"   "+order.getDeskid());
        System.out.println(list.size()+" "+desk.getIdnum()+" "+desk.getDname());
        Print p = new Print(list,desk.getIdnum(),desk.getDname());
        p.startPrint(p);


        return "success";
    }

    @ResponseBody
    @RequestMapping("/print_order")
    public String print_order(String orderid)
    {

        Order order = iorder.getOrderById(orderid);
        List<SubFood>  list = ifood.getFoodListByOrderid(order.getId());

        Desk desk = idesk.getDeskById(order.getDeskid());
        Print p = new Print(list,desk.getIdnum(),desk.getDname());
        p.startPrint(p);


        return "success";
    }


    @ResponseBody
    @RequestMapping("/delete_area")
    public String delete_area(String id)
    {
        iarea.delAreaGroup(id);
        iarea.delArea(id);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/del_order")
    public String del_order(String id,String orderid)
    {

        Map map = new HashMap<String, String>();
        map.put("id", id);
        map.put("orderid", orderid);


        iorder.delOrdFood(map);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/over_order")
    public String over_order(String sum,String id,String deskid,HttpServletRequest request)
    {
        /*t_order 将订单状态修改为结账状态*/
        Map map = new HashMap<String, String>();
        map.put("id", id);
        map.put("sum", sum);

        iorder.upOrdFoodStatToOver(map);


        /*修改台号为初始状态*/
        Desk tdesk = idesk.getDeskById(deskid);

        /*判断当前台号是否为被合并台号*/
        if(tdesk.getOthid()!=null && tdesk.getOthid().trim().length()>0)
        {
            /*若为被合并台号则将目标台号状态改为初始状态*/
            idesk.upDeskIsUsed(tdesk.getOthid());

            /*判断当前台号是否被合并*/
            List<Desk> list = idesk.getDeskByOthId(tdesk.getOthid());
            for(Desk desk:list)
            {
                if(desk!=null)
                {
                    desk.setFlag("0");
                    desk.setOthid("");
                    desk.setBegintime("");
                    idesk.upDeskColInfo(desk);
                }
            }

        }else
        {
            /*把当前台号改为初始状态*/
            idesk.upDeskIsUsed(deskid);


            List<Desk> list = idesk.getDeskByOthId(deskid);
            for(Desk desk:list)
            {
                if(desk!=null)
                {
                    desk.setFlag("0");
                    desk.setOthid("");
                    desk.setBegintime("");
                    idesk.upDeskColInfo(desk);
                }
            }
        }





        ServletContext application=request.getSession().getServletContext();
        application.removeAttribute(deskid);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/delete_food")
    public String delete_food(String id,HttpServletResponse response)
    {
        Food food = ifood.findById(id);
        String[] flist = food.getImage().split(",");
        for(String file:flist){
            File f = new File(UploadAction.prop.getProperty("imgpath")+file);
            f.delete();
        }

        ifood.delete(id);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/get_Max")
    public String get_Max()
    {

        String max = ifoodtype.getMax();
        return max;
    }

    @ResponseBody
    @RequestMapping("/get_Min")
    public String get_Min()
    {
        String min =ifoodtype.getMin();
        return min;
    }

    @RequestMapping("/show_fooddetail")
    public String show_fooddetail(String id,ModelMap model)
    {
        Food food = ifood.findById(id);

        model.put("food", food);

        String imglist = food.getImage();
        String [] arr = imglist.split(",");

        List<String> list = new ArrayList<String>();
        for(String str :arr)
        {
            list.add(str);
        }

        model.put("list", list);

        return "showFoodDetail";
    }

    @RequestMapping("/show_foodImg")
    public String show_foodImg(String id,ModelMap model)
    {
        Food food = ifood.findById(id);

        model.put("food", food);

        String imglist = food.getImage();
        String [] arr = imglist.split(",");

        List<String> list = new ArrayList<String>();
        for(String str :arr)
        {
            list.add(str);
        }

        model.put("list", list);

        return "p_foodImg";
    }

    @RequestMapping("/show_deskdetail")
    public String show_deskdetail(String areaid,ModelMap model)
    {
        int SIZE=7;
        List alist = new ArrayList<List>();
        List<Desk> dlist = idesk.getDeskListById(areaid);

        List<Desk> itemlist = new ArrayList<Desk>();
        for(int i=0;i<dlist.size();i++)
        {
            Desk it = dlist.get(i);
            if(it.getFlag().equals("1"))
            {
                String date2 = it.getBegintime();
                String diff =DateFormatUtils.getTimesToNow(date2);

                it.setBegintime(diff);

            }
            if(it.getFlag().equals("2"))
            {
                Desk desk = idesk.getDeskById(it.getOthid());
                it.setOthid(desk.getIdnum());
            }
            itemlist.add(dlist.get(i));
            if((i+1)%SIZE==0)
            {
                alist.add(itemlist);
                itemlist  = new ArrayList<Desk>();
            }
        }

        alist.add(itemlist);


        model.put("list", alist);
        model.put("areaid", areaid);

        return "show_deskDetail";
    }

    @ResponseBody
    @RequestMapping("/get_desknum")
    public String get_desknum()
    {
        String num =idesk.getMax();
        //System.out.println("snum="+num);
        if(num==null)
        {
            num="1";
        }else
        {
            int inum = Integer.parseInt(num)+1;
            //System.out.println("inum="+inum);
            num = String.valueOf(inum);
            //System.out.println("num="+num);
        }
        return num;
    }

    @ResponseBody
    @RequestMapping("/add_order")
    public String add_order(String foodid,String deskid,String count,String flag)
    {

        Desk desk = idesk.getDeskById(deskid);
        if(desk !=null)
        {
            if(desk.getOthid()!=null && desk.getOthid().trim().length()>0)
            {
                deskid=desk.getOthid();
            }
        }




        Order order = iorder.getOrderByDeskId(deskid);
        if(order==null)
        {

            /*新增订单*/
            order = new Order();
            UUID uuid = UUID.randomUUID();
            order.setId(uuid.toString());
            order.setDeskid(deskid);
            order.setFlag("0");
            order.setOrgdate(DateFormatUtils.getCurDate());
            order.setOrgtime(DateFormatUtils.getCurTime());
            iorder.addOrder(order);
            /*修改餐桌状态为使用中*/
            Map map = new HashMap<String, String>();
            map.put("id", deskid);
            String datetime = DateFormatUtils.getCurDateTime();
            map.put("time", datetime);
            idesk.upDeskStat(map);
        }else if(order.getFlag().equals("2")&&flag==null)
        {
            return "failed";
        }

        Map map = new HashMap<String, String>();
        UUID uuid = UUID.randomUUID();
        map.put("id", uuid.toString());
        map.put("orderid", order.getId());
        map.put("foodid", foodid);
        map.put("orderdate", DateFormatUtils.getCurDate());
        map.put("count",count);
        iorder.addOrdFood(map);

        return "success";
    }


    @ResponseBody
    @RequestMapping("/updateCount")
    public String updateCount(String id,String count)
    {
        Map map = new HashMap<String, String>();
        map.put("id", id);
        map.put("count", count);

        ifood.updateCount(map);
        return "success";
    }

}
